﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CashResource;
using System.Data.Sql;
using Cash;
using CashCommon;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;



namespace CashConnect
{
    [Serializable]
    public partial class FormConnect : Form
    {
        public FormConnect()
        {
            InitializeComponent();
            this.Text = CommonText.MainForm_Title;
        }

        #region События формы

        private void frmConnect_Load(object sender, EventArgs e)
        {
            this.Text = CommonText.ConnectForm_Title;
            
            // Загрузка файла настроек соединения
            Config.Reload();

            FillComboboxes();
            
            // Установка всплывающих подсказок для кнопок
            new ToolTip().SetToolTip(btnClear, CommonText.FormConnectClearServers);
            new ToolTip().SetToolTip(btnCatalogClear, CommonText.FormConnectClearCatalogs);
            new ToolTip().SetToolTip(btnRefreshServers, CommonText.FormConnectRefreshServers);
        }
        private void btnRefreshServers_Click(object sender, EventArgs e)
        {
            _frmProgress = new FrmProgress(CommonText.ProgressFormTitleSqlServers);
            BackgroundWorker bgw = new BackgroundWorker();
            bgw.DoWork += new DoWorkEventHandler(bgw_DoWorkGetSqlServers);
            bgw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgw_RunWorkerCompletedGetSqlServers);
            bgw.RunWorkerAsync();
            _frmProgress.ShowDialog();
            Config.Save();
            Config.Reload();
        }
        private void cbxCatalog_DropDown(object sender, EventArgs e)
        {

        }
        private void btnConnect_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                if (cbxAuth.SelectedIndex == 0)
                    WFSql.DB.ConnectWin(cbxServerName.Text, cbxCatalog.Text, tbUser.Text);
                else
                    WFSql.DB.Connect(cbxServerName.Text, cbxCatalog.Text, tbUser.Text, tbPassword.Text);


                //Сериализация
                Config.Default.ServersList.AddRange((from Object obj in cbxServerName.Items select (ComboBoxItem)obj).ToArray<ComboBoxItem>());
                Config.Default.ServersList.Add(new ComboBoxItem(cbxServerName.Text));

                Config.Default.CatalogsList.AddRange((from Object obj in cbxCatalog.Items select (ComboBoxItem)obj).ToArray<ComboBoxItem>());
                Config.Default.CatalogsList.Add(new ComboBoxItem(cbxCatalog.Text));

                Config.Default.CurrentServer = cbxServerName.Text;
                Config.Default.CurrentAuth = cbxAuth.SelectedIndex;
                Config.Default.CurrentCatalog = cbxCatalog.Text;

                Config.Save();

                this.DialogResult = DialogResult.OK;
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }
        private void btnClose_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
        }
        private void btnClear_Click(object sender, EventArgs e)
        {
            cbxServerName.Items.Clear();
            cbxServerName.Text = "";

            Config.Default.ServersList.Clear();
            Config.Default.CurrentServer = "";

            Config.Save();
            Config.Reload();
        }
        private void btnCatalogClear_Click(object sender, EventArgs e)
        {
            cbxCatalog.Items.Clear();
            cbxCatalog.Text = "";

            Config.Default.CatalogsList.Clear();
            Config.Default.CurrentCatalog = "";

            Config.Save();
            Config.Reload();
        }
        void cbxAuth_SelectedIndexChanged(object sender, EventArgs e)
        {
            ComboBox comboBox = sender as ComboBox;
            if (comboBox != null)
            {
                bool selected = comboBox.SelectedIndex == 1;
                tbPassword.Enabled = selected;
                tbUser.Enabled = selected;
            }
        }
        private void FormConnect_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                btnConnect_Click(null, null);
            if (e.KeyCode == Keys.F1)
                FormConnect_HelpButtonClicked(null, new CancelEventArgs());
        }
        private void FormConnect_HelpButtonClicked(object sender, CancelEventArgs e)
        {
            Tools.GetHelp("Inf_Form_Connect", HelpNavigator.Topic);
            e.Cancel = true;
        }

        #endregion

        #region Helper
        
        private void FillComboboxes()
        {
            // Авторизация
            cbxAuth.SelectedIndexChanged += null;
            cbxAuth.BeginUpdate();
            cbxAuth.Items.Add(CommonText.FormConnectAuthText0);
            cbxAuth.Items.Add(CommonText.FormConnectAuthText1);
            cbxAuth.SelectedIndex = Config.Default.CurrentAuth;
            cbxAuth.SelectedIndexChanged += new EventHandler(cbxAuth_SelectedIndexChanged);
            cbxAuth.EndUpdate();

            // Сервера
            cbxServerName.BeginUpdate();
            cbxServerName.DisplayMember = "Name";
            cbxServerName.Items.AddRange(Config.Default.ServersList.Items.ToArray());
            cbxServerName.Text = Config.Default.CurrentServer;
            cbxServerName.EndUpdate();

            // Базы данных
            cbxCatalog.BeginUpdate();
            cbxCatalog.DisplayMember = "Name";
            cbxCatalog.Items.AddRange(Config.Default.CatalogsList.Items.ToArray());
            cbxCatalog.Text = Config.Default.CurrentCatalog;
            cbxCatalog.EndUpdate();
        }

        #endregion

        #region Threads

        public void bgw_DoWorkGetSqlServers(object sender, DoWorkEventArgs e)
        {
            DataTable dt = SqlDataSourceEnumerator.Instance.GetDataSources();
            if (this.cbxServerName.InvokeRequired)
                BeginInvoke(new MethodInvoker(delegate
                {
                    String[] sa = (from Object obj in cbxServerName.Items select ((ComboBoxItem)obj).Name.ToUpper()).ToArray();
                    cbxServerName.BeginUpdate();
                    foreach (System.Data.DataRow dr in dt.Rows)
                        if(!sa.Contains(dr[0].ToString().ToUpper()))
                            cbxServerName.Items.Add(new ComboBoxItem(dr[0].ToString()));
                    if (cbxServerName.Items.Count > 0)
                        cbxServerName.SelectedIndex = 0;
                    cbxServerName.EndUpdate();
                }));
            else
            {
                cbxServerName.BeginUpdate();
                foreach (System.Data.DataRow dr in dt.Rows)
                    cbxServerName.Items.Add(dr[0].ToString());
                cbxServerName.EndUpdate();
            }
        }
        public void bgw_RunWorkerCompletedGetSqlServers(object sender, RunWorkerCompletedEventArgs e)
        {
            if (_frmProgress != null) 
                _frmProgress.Close();
        }

        #endregion

        private FrmProgress _frmProgress;


    }
}
